// pages/user/pages/bindCouponCard/bindCouponCard.js
var http = require('../../../../service/http.js');
var util = require('../../../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    choosePhotoNum: 1, //可以长传的照片数量
    photoUrlArr: [], //上传图片地址
    birthdayDate: '', //出生日期
    cardInfo: '', //请求的开卡要素


    //提交表单
    isVaildateForm: false, //true-表单验证成功可以提交表单
    showCardSuccessPage: '', //提交表单成功页

    //请求开卡信息参数
    eccode: '', //卡
    itemid: '', //商品id
    entityCode: '', //实体卡卡号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('开卡', options);
    if (options) {
      this.setData({
        itemid: options.itemid,
        eccode: options.eccode
      })
    }
  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    if (app.data.shopInfoTimeOut === true) { //非分享且已经过期，清除店铺信息
      console.log('店铺信息已过期，重新加载 app.checkSession()');
      app.checkSession();
    }

    this.getCardSettings();
  },
  /**
   * 获取开卡设置信息
   */
  getCardSettings: function() {
    http.getReq('/weixin/activeCard/getPropSettings', {
      itemid: this.data.itemid,
      eccode: this.data.eccode
    }, (res)=> {
      console.log('获取开卡设置信息', res);
      this.setData({
        cardInfo: res.data
      })
    })
  },
  /**
   * 更改出生年月日
   */
  bindDateChange: function(e) {
    console.log('bindDateChange', e);
    this.setData({
      birthdayDate: e.detail.value
    })
  },
  /**
   * 选择照片
   */
  choosePhoto: function() {
    let choosePhotoNum = this.data.choosePhotoNum; //可以长传的照片数量
    let photoUrlArr = this.data.photoUrlArr; //上传图片地址
    let canChooseNum = choosePhotoNum - photoUrlArr.length
    if (canChooseNum >= 1) {

      wx.chooseImage({
        count: canChooseNum,
        success: (res)=> {
          console.log(res);
          let chooseImgs = res.tempFilePaths; //已选图片本地路径

          if (photoUrlArr.length > 0) { //原已选图片长度
            photoUrlArr.push(...res.tempFilePaths);
          } else { //没有已选长度
            photoUrlArr = res.tempFilePaths;
          }
          this.setData({
            photoUrlArr: photoUrlArr
          })
        }

      })
    }
  },
  /**
   * 保存优惠卡信息（提交表单）
   */
  saveCardInfo: function(e) {
    console.log('保存优惠卡信息（提交表单）', e);
    this.vaildateForm(e);
    let isVaildateForm = this.data.isVaildateForm;
    let photoUrlArr = this.data.photoUrlArr;

    if (isVaildateForm) {

      http.getReq('/weixin/activeCard/doActive', {
        eccode: e.detail.value.eccode || '',
        activeCardPhone: e.detail.value.cardPhone || '',
        name: e.detail.value.cardUser || '',
        birthday: e.detail.value.birthdayDate ? e.detail.value.birthdayDate.replace(/-/g, '') : '',
        idCard: e.detail.value.idCardNum || '',
        parentTel: e.detail.value.parentPhone || '',
        address: e.detail.value.homeAddress || '',
        entityCardCode: e.detail.value.entityCode || '',
      }, (res)=> {
        console.log('保存优惠卡信息（提交表单）', res);
        //开始上传图片
        if (res.ret) {
          if (photoUrlArr.length > 0) {
            for (let i = 0; i < photoUrlArr.length; i++) {
              wx.uploadFile({
                url: app.data.baseUrl + '/weixin/activeCard/upImg', //仅为示例，非真实的接口地址
                filePath: photoUrlArr[i],
                name: 'file',
                header: {
                  'content-type': 'multipart/form-data'
                },
                formData: {
                  'zjactivecardInfoid': res.data
                },
                success:(res) =>{
                  console.log('上传图片成功', res);
                  if (i == (photoUrlArr.length - 1)) { //最后一张图片上传成功后显示开卡成功
                    this.setData({
                      showCardSuccessPage: true
                    })
                  }
                }
              })
            }
          } else {
            this.setData({
              showCardSuccessPage: true
            })
          }
        }
      });

    }
  },
  /**
   * 验证表单
   */
  vaildateForm: function(e) {

    let cardUser = e.detail.value.cardUser; //用户姓名
    let cardPhone = e.detail.value.cardPhone; //联系电话
    let birthdayDate = e.detail.value.birthdayDate; //出生日期

    let idCardNum = e.detail.value.idCardNum; //身份证号
    let parentPhone = e.detail.value.parentPhone; //家长电话
    let homeAddress = e.detail.value.homeAddress; //家庭住址
    let entityCode = e.detail.value.entityCode || ''; //实体卡卡号
    let photoUrlArr = this.data.photoUrlArr; //照片
    
    console.log('entityCode', entityCode);
    let [isVaildateForm, msg, cardInfo] = [false, '', this.data.cardInfo];
    if (cardInfo.entityCardCode !== '0' && entityCode.trim() === '') {
      msg = "请填实体卡卡号"
    } else if (cardPhone.trim() === '') {
      msg = "请填写联系电话"
    } else if (cardInfo.name !== '0' && cardUser.trim() === '') {
      msg = "请填写用户姓名"
    } else if (cardInfo.birthday !== '0' && birthdayDate.trim() === '') {
      msg = "请选择出生日期"
    } else if (cardInfo.photo !== '0' && photoUrlArr.length < 1) {
      msg = '请上传照片'
    } else if (cardInfo.idCard !== '0' && idCardNum.trim() === '') {
      msg = "请填身份证卡号"
    } else if (cardInfo.parentPhone !== '0' && parentPhone.trim() === '') {
      msg = "请填写家长电话"
    } else if (cardInfo.address !== '0' && homeAddress.trim() === '') {
      msg = "请填写家庭住址"
    }

    //校验填写格式
    else if (!util.testName(cardUser) && cardInfo.name !== '0') {
      msg = '姓名填写有误';
    } else if (!util.textNoCharCode(entityCode) || entityCode.trim().length >10) {
      msg = '实体卡号输入不合法，请检查'
    } else if (!util.testPhone(cardPhone)) {
      msg = '联系电话填写有误';
    } else if (!util.testIdCard(idCardNum) && cardInfo.idCard !== '0') {
      msg = '身份证填写有误';
    } else if (!util.testPhone(parentPhone) && cardInfo.parentPhone !== '0') {
      msg = '家长电话填写有误';
    }

    if (msg === '') {
      isVaildateForm = true;
    } else {
      util.showToast(msg, 1000, 'none', function() {});
      isVaildateForm = false;
    }
    this.setData({
      isVaildateForm: isVaildateForm
    })

  },
  /**
   * 预览图片
   */
  previewImage: function(e) {
    let preIndex = e.currentTarget.dataset.index;
    let photoUrlArr = this.data.photoUrlArr;
    util.previewImg(photoUrlArr, photoUrlArr[preIndex]);
  },
  /**
   * 删除图片
   */
  delImg: function(e) {
    console.log('删除图片', e);
    let delIndex = e.currentTarget.dataset.index;
    let photoUrlArr = this.data.photoUrlArr;
    photoUrlArr.splice(delIndex, 1);
    this.setData({
      photoUrlArr: photoUrlArr
    })
  },
  /**
   * 预约成功查看订单
   */
  backToOrder: function() {
    wx.navigateBack({
      delta: 1,
    })
  },
})